﻿Imports NHibernate
Imports System.Reflection

Public NotInheritable Class Persister
    Implements IDisposable

    Private Shared mySessionFactory As NHibernate.ISessionFactory

    Public Shared Function OpenSession() As ISession
        Return mySessionFactory.OpenSession()
    End Function

    Public Shared Sub InitialNhibernateLoad(ByVal dbPath As String, Optional ByVal showSql As Boolean = False)

        Dim cfg As New NHibernate.Cfg.Configuration()
        cfg.Properties(NHibernate.Cfg.Environment.ConnectionProvider) = "NHibernate.Connection.DriverConnectionProvider"
        cfg.Properties(NHibernate.Cfg.Environment.Dialect) = "NHibernate.Dialect.MsSql2005Dialect"
        cfg.Properties(NHibernate.Cfg.Environment.ConnectionDriver) = "NHibernate.Driver.SqlClientDriver"
        cfg.Properties(NHibernate.Cfg.Environment.ConnectionString) = dbPath

        'Extra (optional) settings
        cfg.Properties(NHibernate.Cfg.Environment.ShowSql) = showSql
        'cfg.Properties(NHibernate.Cfg.Environment.ReleaseConnections) = "on_close"

        cfg.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.[Default].Serialize(Assembly.GetCallingAssembly()))

        ' Build the SessionFactory
        mySessionFactory = cfg.BuildSessionFactory()
    End Sub

    Public Shared Property PersistorSessionFactory() As ISessionFactory
        Get
            Return mySessionFactory
        End Get
        Set(ByVal value As ISessionFactory)
            mySessionFactory = value
        End Set
    End Property

    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not forget to close the session factory when you are done with it
        mySessionFactory.Close()
        If Not IsNothing(mySessionFactory) Then
            mySessionFactory.Dispose()
        End If
    End Sub
End Class
